import router from "./router";
import { getToken, getRouters } from "./utils/auth";
import { isMoblie } from "./utils/public";
import store from "./store";


/*
 * 判断是否cook里的token是否有效
 * 如果有效则继续跳转到访问页面
 * 无效则跳转至登录页面
 * */

router.beforeEach(function (to, from, next) {
  try {
    let jumpPath = to.path;
    let nextUrlList = ["/login", "/error"]; //此处定义无需权限判断的访问路径
    if (nextUrlList.indexOf(jumpPath) < 0) {
      if (!getToken()) {
        //判断是否有访问令牌
        //在着可以判断做PC端或者是手机端
        next("/login");
      } else {
        if (!store.getters.routeFlag) {
          let routerArr = getRouters();
          if (!routerArr.length) {
            next({
              name: "ErrorPage",
              params: { errorType: "您没有访问权限，请联系管理员" }
            });
            return;
          }
          routerArr.forEach(route => {
            router.addRoute(route);
          });
          store.dispatch("user/setRouteFlag", true);
        }
        if (to.matched.length === 0 && jumpPath !== "/") {
          next("/");
          return;
        }
        if (jumpPath === "/") {
          let defaultUrl = store.getters.userInfo.firstPath;
          if (isMoblie()) defaultUrl = `/mobile/${defaultUrl.jump}`;
          next(defaultUrl);
        } else {
          next();
        }
      }
    } else {
      next();
    }
  } catch (e) {
    next("/error");
  }
});